<template>
  <!-- 发起预算 -->
  <a-card :bordered="false" style="overflow-y: hidden;overflow-x: scroll;">
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="48">
          <a-col :md="8" :sm="24">
            <a-form-item label="预算周期">
              <a-select placeholder="请选择预算周期" v-model="pagination.type" @change="selectType">
                <a-select-option :value="item.id" v-for="(item, index) in typeList" :key="index">{{
                  item.name
                }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item label="预算日期">
              <a-date-picker
                placeholder="请选择预算开始日期"
                v-model="pagination.budgetDate"
                :value-format="formatTime"
                style="width: 100%;" />
            </a-form-item>
          </a-col>
          <a-col :md="!advanced && 8 || 24" :sm="24">
            <span
              class="table-page-search-submitButtons"
              :style="advanced && { float: 'right', overflow: 'hidden' } || {}">
              <a-button type="primary" @click="onSearch">查询</a-button>
              <a-button style="margin-left: 8px" @click="onReset">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <div class="filter-container">
    </div>
    <a-back-top />
    <div>
      <a-button type="primary" @click="onFill()" :visible="visibleBtn" :loading="loadingBtn">
        填报
      </a-button>
      <table class="vtable">
        <thead>
          <div style="background-color: #e8e8e8;display: flex;">
            <div
              style="flex: 1;"
              v-for="(item, index) in headersSource"
              :key="index"
              :style="item.hidden ? 'display: none;' : ''">
              <th class="thead-th" v-if="index != 0" style="display: flex;">
                <span v-if="index != 0" style="display: inline-block;flex: 1;">{{ item.name }}</span>
              </th>
            </div>
          </div>
        </thead>
        <tbody>
          <div v-for="(row, rowId) in newdataSource " :key="rowId" style="display: flex;">
            <tr style="height: 40px;display: flex;" v-if="newdataSource.length > 0 ? row.datas[0] : false">
              <template v-for="(it, itId) in row.datas">
                <div v-if="headersSource[itId].hidden == false">
                  <template v-if="!headersSource[itId].primary">
                    <a-input class="row-td" :value="it" :disabled="true" />
                  </template>
                  <template v-else>
                    <a-input
                      class="row-td"
                      :value="it"
                      type="number"
                      @change="e => handleChange(e.target.value, rowId, itId)"
                      :disabled="false" />
                  </template>
                </div>
              </template>
            </tr>
            <tr style="height: 40px;display: flex;" v-else>
              <template v-for="(it, itId) in row.datas">
                <div v-if="headersSource[itId].hidden == false">
                  <a-input class="row-td" :value="it" :disabled="true" />
                </div>
              </template>
            </tr>
          </div>
        </tbody>
      </table>
    </div>
    <fillDataModal ref="fillDataModal"></fillDataModal>
  </a-card>
</template>

<script>

import { getBudgetsLaunch, addProjectData } from '@/api/budget'
import fillDataModal from './fillData'
import { Modal } from 'ant-design-vue'

// import { STable } from '@/components'

export default {
    // STable
    components: { fillDataModal },
    data () {
        return {
            // 高级搜索 展开/关闭
            advanced: false,
            headersSource: [],
            dataSource: [],
            newdataSource: [],
            newArr: [], // 保存修改的id
            dialog: {
                save: false,
                submit: false,
                audit: false
            },
            loading: false,
            pagination: {
                type: undefined,
                budgetDate: ''
            },
            typeList: [
                { id: 1, name: '年度预算' },
                { id: 2, name: '月度预算' }
            ],
            formatTime: 'YYYY-MM-DD',

            // 表头
            columns: [
                {
                    title: '规则编号',
                    dataIndex: 'no',
                    width: 90
                },
                {
                    title: '描述',
                    dataIndex: 'description',
                    width: '150px',
                    scopedSlots: { customRender: 'description' }
                },
                {
                    title: '服务调用次数',
                    dataIndex: 'callNo',
                    width: '150px',
                    // sorter: true,
                    // needTotal: true,
                    scopedSlots: { customRender: 'callNo' }
                    // customRender: (text) => text + ' 次'
                },
                {
                    title: '状态',
                    dataIndex: 'status',
                    width: '100px',
                    // needTotal: true,
                    scopedSlots: { customRender: 'status' }
                },
                {
                    title: '更新时间',
                    dataIndex: 'updatedAt',
                    width: '200px',
                    // sorter: true,
                    scopedSlots: { customRender: 'updatedAt' }
                },
                {
                    table: '操作',
                    dataIndex: 'action',
                    width: '120px',
                    scopedSlots: { customRender: 'action' }
                }
            ],
            // 加载数据方法 必须为 Promise 对象
            // loadData: () => {
            //     let result = { "pageSize": 10, "pageNo": 1, "totalCount": 20, "totalPage": 20, "data": [{ "key": 1, "id": 1, "no": "No 1", "description": "这是一段描述", "callNo": 370, "status": 1, "updatedAt": "1991-09-14 13:21:33", "editable": false }, { "key": 2, "id": 2, "no": "No 2", "description": "这是一段描述", "callNo": 361, "status": 3, "updatedAt": "2010-03-28 02:31:02", "editable": false }, { "key": 3, "id": 3, "no": "No 3", "description": "这是一段描述", "callNo": 274, "status": 2, "updatedAt": "1978-03-03 20:48:09", "editable": false }, { "key": 4, "id": 4, "no": "No 4", "description": "这是一段描述", "callNo": 871, "status": 3, "updatedAt": "1991-07-24 12:09:47", "editable": false }, { "key": 5, "id": 5, "no": "No 5", "description": "这是一段描述", "callNo": 673, "status": 0, "updatedAt": "2001-02-13 10:18:23", "editable": false }, { "key": 6, "id": 6, "no": "No 6", "description": "这是一段描述", "callNo": 195, "status": 2, "updatedAt": "1991-06-05 19:27:55", "editable": false }, { "key": 7, "id": 7, "no": "No 7", "description": "这是一段描述", "callNo": 330, "status": 2, "updatedAt": "1983-05-05 23:51:49", "editable": false }, { "key": 8, "id": 8, "no": "No 8", "description": "这是一段描述", "callNo": 231, "status": 2, "updatedAt": "1973-06-29 20:12:09", "editable": false }, { "key": 9, "id": 9, "no": "No 9", "description": "这是一段描述", "callNo": 812, "status": 2, "updatedAt": "1984-07-22 10:08:33", "editable": false }, { "key": 10, "id": 10, "no": "No 10", "description": "这是一段描述", "callNo": 2, "status": 1, "updatedAt": "1972-11-11 10:00:44", "editable": false }] }
            //     return new Promise((resolve, reject) => {
            //         resolve(result)
            //     }).catch(() => console.log('Oops errors!'))

            // },
            selectedRowKeys: [],
            selectedRows: [],
            visibleBtn: false,
            loadingBtn: false,
            inputArr: []
        }
    },
    mounted () {

    },
    computed: {

    },
    methods: {
        // 计算比率
        // 本月比上月情况=（本月数字-上月数字）/上月数字，如果本月大于上月，结果就是正数，即上升，反之为下降
        rateCompute (a, b) {
            if (a > 0 || b > 0) {
                if (a > b) return Math.round(((b - a) / a) * 100) + '%'
                else if (b > a) return Math.round(((b - a) / b) * 100) + '%'
                else return '0%'
            } else {
                return '0%'
            }
        },
        // 获取填报改变的值
        handleChange (value, rowId, itId) {
            console.log(value, rowId, itId)
            if (value > 0) { // 01 = > 1
                if (value[0] == 0) {
                    value = value.substr(1)
                }
            } else if (value == 0) { // 00 => 0
                value = value.slice(0, 1)
            }
            this.newdataSource.forEach((item, index) => {
                if (index == rowId) {
                    item.datas.splice(itId, 1, value)
                    // 获取上个月和当前预算的数据，动态改变提升利率
                    const pre = item.datas[itId - 1]
                    const now = item.datas[itId]
                    item.datas.splice(itId + 1, 1, this.rateCompute(Number(pre), Number(now)))
                    if (item.datas[0] != '') this.newArr.push(item.datas[0])
                    this.newArr = Array.from(new Set(this.newArr))
                }
            })
        },
        edit (row) {
            row.editable = true
            // row = Object.assign({}, row)
        },
        del (row) {
            this.$confirm({
                title: '警告',
                content: `真的要删除 ${row.no} 吗?`,
                okText: '删除',
                okType: 'danger',
                cancelText: '取消',
                onOk () {
                    console.log('OK')
                    // 在这里调用删除接口
                    return new Promise((resolve, reject) => {
                        setTimeout(Math.random() > 0.5 ? resolve : reject, 1000)
                    }).catch(() => console.log('Oops errors!'))
                },
                onCancel () {
                    console.log('Cancel')
                }
            })
        },
        save (row) {
            console.log(row)
            row.editable = false
        },
        cancel (row) {
            row.editable = false
        },
        onSelectChange (selectedRowKeys, selectedRows) {
            this.selectedRowKeys = selectedRowKeys
            this.selectedRows = selectedRows
        },

        // 填报预算项目
        onFill () {
            // this.$nextTick(() => {
            //     this.$refs.fillDataModal.open()
            // })
            const { type, budgetDate } = this.pagination
            console.log(type, budgetDate)
            if (type == undefined && budgetDate == '') {
                this.$notification['error']({
                    message: '提示',
                    description: '请选择预算周期和预算日期',
                    duration: 8
                })
                return
            }
            // 获取项目id 的下标
            const projectId = (this.headersSource || []).findIndex((item) => item.columnId === 'projectId')
            const filterArr = this.newdataSource.filter(item => {
                return this.newArr.includes(item.datas[projectId])
            })
            // 获取需要填报的下标
            const budgetAmountId = (this.headersSource || []).findIndex((item) => item.primary === true)
            let objectArr = []
            objectArr = filterArr.map(item => {
                const obj = {}
                if (item.datas[budgetAmountId] > 0) {
                    // 获取项目id和项目值
                    obj.projectId = item.datas[projectId]
                    obj.value = item.datas[budgetAmountId]
                    return obj
                } else {
                    return ''
                }
                // 获取项目id和项目值
                // obj.projectId = item.datas[0]
                // obj.value = item.datas[item.datas.length - 1]
                // return obj
            }).filter(item => item)
            if (objectArr.length == 0) {
                this.$notification['error']({
                    message: '提示',
                    description: '请编辑预算项目',
                    duration: 8
                })
                return
            }
            if (objectArr.length > 0) {
                const par = {
                    type,
                    dateTime: budgetDate,
                    projects: objectArr
                }
                addProjectData(par).then(res => {
                    if (res.code === 200) {
                        this.$notification['success']({
                            message: '提示',
                            description: '填报成功！',
                            duration: 8
                        })
                        this.visible = false
                        this.$emit('success')
                    } else {
                        this.$notification['error']({
                            message: '提示',
                            description: res.message,
                            duration: 8
                        })
                    }
                    this.visibleBtn = false
                    this.loadingBtn = false
                }).finally(res => {
                    this.loadingBtn = false
                    this.visibleBtn = false
                })
            } else {
                this.$notification['error']({
                    message: '提示',
                    description: '请填报数据',
                    duration: 8
                })
            }
        },
        selectType (value) {
            if (value == 1) this.formatTime = 'YYYY'
            else this.formatTime = 'YYYY-MM-DD'
        },
        // 高级搜索切换
        toggleAdvanced () {
            this.advanced = !this.advanced
        },
        // 搜索
        onSearch () {
            this.pagination.current = 1
            this.pagination.pageSize = 6
            this.tableData()
        },
        // 重置
        onReset () {
            this.pagination = {
                type: undefined,
                budgetDate: ''
            }
            this.tableData()
        },

        tableData () {
            this.loading = true
            this.dialog.save = false
            const par = {
                ...this.pagination
            }
            if (par.type == undefined && par.budgetDate == '') {
                this.$notification['error']({
                    message: '提示',
                    description: '请选择预算周期和预算日期',
                    duration: 8
                })
                return
            }
            if (par.type == undefined) {
                this.$notification['error']({
                    message: '提示',
                    description: '请选择预算周期',
                    duration: 8
                })
                return
            }
            if (par.budgetDate == '') {
                this.$notification['error']({
                    message: '提示',
                    description: '请选择预算日期',
                    duration: 8
                })
                return
            }
            // if (par.type == undefined) par.type = '2'
            // if (par.budgetDate == '') {
            //     let time = new Date()
            //     let nowTime = this.timestampToTime(time.toLocaleString('en-US', { hour12: false }).split(" "))
            //     par.budgetDate = nowTime
            // } else {

            if (par.type == 1) par.budgetDate = par.budgetDate + '-01-01'
            // }

            getBudgetsLaunch(par).then(res => {
                console.log(res)
                if (res.code == 200) {
                    this.dataSource = res.data.lines
                    const lines = res.data.lines
                    // this.headersSource = res.data.headers
                    // this.newdataSource = res.data.lines
                    this.headersSource = res.data.headers
                    this.headersSource.push({
                        'columnId': '',
                        'name': '提升比率',
                        'hidden': false,
                        'primary': false
                    })
                    // 获取填报的下标
                    const budgetAmountId = (this.headersSource || []).findIndex((item) => item.primary === true)
                    this.newdataSource = lines.map((item, index) => {
                        if (index == budgetAmountId) {
                            // 根据填报位置，获取上一个月份的信息
                            const pre = item.datas[index - 1]
                            const now = item.datas[budgetAmountId]
                            item.datas.push(this.rateCompute(Number(pre), Number(now)))
                        } else {
                            item.datas.push('0%')
                        }
                        const obj = {
                            ...item
                        }
                        return obj
                    })
                } else {
                    this.$notification['error']({
                        message: '提示',
                        description: res.message,
                        duration: 8
                    })
                }
                this.loading = false
            })
        },

        onDel (row) {
            const _this = this
            Modal.confirm({
                title: '删除信息',
                content: '确定要删除吗？',
                onOk: () => {
                    deleteTenants(row.tenantId).then(res => {
                        if (res.code == 200) {
                            _this.tableData()
                            _this.$message.success('删除成功')
                        } else {
                            _this.$message.error(res.message)
                        }
                    })
                }
            })
        },
        timestampToTime (times) {
            const time = times[1]
            let mdy = times[0]
            mdy = mdy.split('/')
            const month = parseInt(mdy[0])
            const day = parseInt(mdy[1])
            const year = parseInt(mdy[2])
            return year + '-' + month + '-' + day
        }
    }
}
</script>

<style scoped lang="less" >
.thead-th {
    // width: 160px;
    width: 100%;
    padding: 10px;

}

.row-td {
    // width: 150px;
    width: 100%;
    padding: 10px;
    border: 1px solid #e8e8e8;
    margin: -5px 0;
    flex: 1;
}

// .thead-tr {
//     background-color: #e8e8e8;
//     border-top-right-radius: 4px;
//     border-top-left-radius: 4px;
//     display: flex;
// }

// .vth {
//     flex: 1;
//     display: flex;
//     justify-content: center;
//     align-items: center;
//     padding: 10px;
// }

.vtd-box {
    // overflow-y: hidden;
    // overflow-x: scroll;

    // .vtd {
    //     width: 150px;
    //     padding: 0 6px;
    //     height: 60px;
    //     line-height: 60px;
    //     border: 1px solid #e8e8e8;

    // }

    // 1,4,7,10 的单元格
    // .vtd:nth-child(3n+1) {
    //     /* 添加样式 */
    //     border-left: 2px solid #e8e8e8;
    // }
    // 3,6,9,13 的单元格
    // .vtd:nth-child(3n) {
    //     /* 添加样式 */
    //     border-right: 2px solid #e8e8e8;
    // }
}

.send-display-container {
    width: 100%;
    background-color: #ffffff;
    padding: 24px;
}

.filter-container {
    display: flex;
    align-items: center;
    padding-bottom: 24px;
    justify-content: left;

    .label {
        padding-right: 20px;

        white-space: nowrap;
    }

    .input-container {
        width: 300px;
        margin-right: 20px
    }

    .btn {
        margin-right: 20px;

    }
}

/deep/ .ant-modal {
    min-width: 700px;
    margin-left: 30%;
}
</style>
